package cn.jetpiece.cloud.joss.app.core.exception;

import cn.hutool.core.bean.BeanUtil;
import cn.jetpiece.cloud.model.exception.ServiceException;
import cn.jetpiece.cloud.model.exception.enums.CommonExceptionEnum;
import cn.jetpiece.cloud.model.response.Result;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.web.context.request.WebRequest;

import java.util.Map;

/**
 * 系统管理未知错误异常重写
 *
 * @author XuJZ
 */
public class SystemErrorAttributes extends DefaultErrorAttributes {

    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
        Throwable throwable = this.getError(webRequest);
        if (throwable instanceof ServiceException) {
            ServiceException serviceException = (ServiceException) throwable;
            return BeanUtil.beanToMap(Result.error(serviceException.getCode(), serviceException.getMessage()));
        } else {
            return BeanUtil.beanToMap(Result.error(CommonExceptionEnum.SERVICE_ERROR.getCode(), CommonExceptionEnum.SERVICE_ERROR.getMessage()));
        }
    }

}
